package org.jage.student.missevo.solution.migration;

import java.util.List;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.jage.address.AgentAddress;
import org.jage.address.IAgentAddress;
import org.jage.agent.IAgent;
import org.jage.platform.component.provider.IComponentInstanceProvider;
import org.jage.platform.component.provider.IComponentInstanceProviderAware;
import org.jage.property.ClassPropertyContainer;
import org.jage.property.InvalidPropertyPathException;
import org.jage.query.AgentEnvironmentQuery;


public class RandomDestinationMigration extends ClassPropertyContainer implements IMigration, IComponentInstanceProviderAware {

	private List<IAgentAddress> agentAddresses;

	private IComponentInstanceProvider provider;

	private AgentEnvironmentQuery<IAgent, IAgent> emptyQuery;

	private static final Logger log = LoggerFactory.getLogger(RandomDestinationMigration.class);

	@SuppressWarnings("unchecked")
    @Override
	public AgentAddress migrate(Collection<?> queryResult, IAgent agent) {
		agentAddresses = new LinkedList<IAgentAddress>();
		IAgentAddress target = null;

		if (queryResult.size() > 0) {
			log.info("Agent: {} can migrate to following environments:", agent.getAddress());
			for (IAgent entry : (Collection<IAgent>)queryResult) {
				IAgentAddress address;
				try {
					address = (IAgentAddress)entry.getProperty("address").getValue();
					log.info("   {}", address);
					agentAddresses.add(address);
				} catch (InvalidPropertyPathException e) {
					log.error("Invalid property path", e);
				}
			}
			int addressNum = new Random().nextInt(agentAddresses.size());

			target = agentAddresses.get(addressNum);
			log.info("chosen: {}", target);

		}
		return (AgentAddress)target;
	}

	@Override
	public AgentEnvironmentQuery<IAgent, IAgent> query() {
		if (emptyQuery == null) {
			emptyQuery = new AgentEnvironmentQuery<IAgent, IAgent>();
		}
		return emptyQuery;
	}

	@Override
	public void setInstanceProvider(IComponentInstanceProvider provider) {
		this.provider = provider;
	}

}